package com.pingpang.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.pingpang.websocketchat.ChannelManager;

@RestController
@RequestMapping("/user")
public class Chat {
	@RequestMapping("/index")
	public ModelAndView index() {
		return new ModelAndView("index");
	}

	@RequestMapping("/chat")
	public ModelAndView chat(String userName, String userCode) {
		if (null == userName || "".equals(userName) || null == userCode || "".equals(userCode)) {
			return new ModelAndView("index");
		}

		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		//String scheme = request.getScheme();// http
		String serverName = request.getServerName();// localhost
		//int serverPort = request.getServerPort();// 8080
		//String contextPath = request.getContextPath();// 项目名
		//String url = scheme + "://" + serverName + ":" + serverPort + contextPath;// http://127.0.0.1:8080/test
		//String url = serverName;
		ModelAndView mav = new ModelAndView();
        if(null != ChannelManager.getChartUser(userCode)) {
        	mav.setViewName("index");
        	mav.addObject("errorMsg", "用户编码已存在，请换个编码!");
        	return mav;
        }		
        
        request.getSession().setAttribute("user", userCode);
        
        mav.setViewName("chat");
		mav.addObject("userName", userName);
		mav.addObject("userCode", userCode);
		mav.addObject("chatPath", serverName);
		return mav;
	}
}
